package cool.mtc.swagger;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static springfox.documentation.builders.BuilderDefaults.nullToEmpty;

/**
 * @author 明河
 */
public class SwaggerUiWebMvcConfigurer implements WebMvcConfigurer {
    private final String baseUrl;

    public SwaggerUiWebMvcConfigurer(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(this.fixup(this.baseUrl) + "/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        String url = this.fixup(this.baseUrl);
        registry.addViewController(url + "/swagger-ui.html")
                .setViewName("redirect:" + url + "/swagger-ui/index.html");
        registry.addViewController(url + "/swagger-ui/")
                .setViewName("forward:" + url + "/swagger-ui/index.html");
    }

    private String fixup(String url) {
        return StringUtils.trimTrailingCharacter(nullToEmpty(url), '/');
    }
}
